Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
How to drop null elements but not undefined when using `arr.flatMap((f) => f ?? [])`?

I've written a function that removes null values from an array:

const dropNull = <T,>(arr: T[]): T[] => {
    return arr.flatMap((f) => f ?? []); // depends >= ES2019
};

For example:

const myArr1 = ['foo', 'bar', 'baz', null]
const output1 = dropNull(myArr1) 
console.log(output1) // => ["foo", "bar", "baz"] 

However, I realized that it also removes undefined values.

const myArr2 = ['foo', 'bar', 'baz', null, undefined]
const output2 = dropNull(myArr2)
console.log(output2) // => ["foo", "bar", "baz"] 

Is there a way to just tweak the current dropNull() in order to remove null but not undefined? That is, I know I could have re-written the function as:

const dropNull2 = <T,>(arr:T[]): T[] => {
    return arr.filter(element => element !== null)
}

But I like the arr.flatMap((f) => f ?? []) style. Is there a small change to it so it will drop only null but not undefined?

TS playground

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use the ternary operators instead

return arr.flatMap((f) => f === null ? [] : f);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda